<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        body{
            height: 1500px;
        }
        .item img{
            width: 240px;
            padding:10px;
        }
        .item{
            border: 1px solid #eee;
            float: left;
            font-size: 0;
        }
        
    </style>
</head>
<body>
    <div id="app">
        
    </div>
    <script>
        http()
        $(window).scroll(function(){
            if(isReachBottom()){
                http();
            }
        })
        function isReachBottom(){
            var scrollTop = $(window).scrollTop()
            var windowHeight = $(window).height()
            var dh = $(document).height()
            var sum = scrollTop+windowHeight
            return (dh-250<sum)? true:false
        }
        function http(){
            $.ajax({
                url:"http://192.168.4.18:8000/more",
                type:"get",
                success:res=>{
                res.forEach(item=>{
                    var template=`
                    <div class="item"><img src=${item.imageUrl} alt=""></div>
                    `
                    $("#app").append(template)
                })
                setTimeout(sort,100)
                }
            })
        }
        function sort(){
            /* 1.得到一排放置几个元素 */
            var ww = $(window).width()
            var box = $(".item").outerWidth()
            var num = Math.floor(ww/box)
            /* 2.定义一个数组获取第一排元素的height */
            var arr = []
            $(".item").each((index,value)=>{
                if(index<num){
                    // console.log(value);
                    var height = $(value).outerHeight()
                    arr.push(height)
                }else{
                    /* 3.将元素放置在最小高度的位置，同时将数组重置 */
                    var minHeight = Math.min(...arr)
                    var index  = arr.indexOf(minHeight);
                    var offsetLeft = $(".item").eq(index).offset().left;
                    $(value).css({
                        position:"absolute",
                        left:offsetLeft,
                        top:minHeight
                    })
                    arr[index] = minHeight+$(value).outerHeight()
                }
            })
        }
    
            
    </script>
</body>
</html>